// 引入所需模块
const WebSocket = require('ws');
const http = require('http');

// 创建一个 HTTP 服务器
const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('WebSocket server is running.\n');
});

// 创建 WebSocket 服务器
const wss = new WebSocket.Server({ server });

// 监听连接事件
wss.on('connection', (ws) => {
    console.log('New client connected!');

    // 立即发送一条消息给前端
    ws.send(`欢迎连接！当前时间是: ${new Date().toLocaleTimeString()}`);
    
    // 启动定时器，每 2 秒发送一条数据给前端
    const interval = setInterval(() => {
        ws.send(`新消息: ${new Date().toLocaleTimeString()}`);
    }, 2000);

    // 监听客户端关闭连接事件
    ws.on('close', () => {
        console.log('Client disconnected!');
        clearInterval(interval); // 清除定时器
    });

    // 监听客户端发来的消息
    ws.on('message', (message) => {
        console.log(`Received: ${message}`);
    });
});

// 启动服务器
const PORT = 8080;
server.listen(PORT, () => {
    console.log(`Server is listening on http://localhost:${PORT}`);
});
